package com.eduplatform.service.impl;

import com.eduplatform.service.AIProxyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI代理服务实现类
 * 负责与外部AI API通信并获取返回结果
 */
@Service
public class AIProxyServiceImpl implements AIProxyService {

    private static final Logger logger = LoggerFactory.getLogger(AIProxyServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    // DeepSeek API URL和密钥
    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/chat/completions";
    private static final String DEEPSEEK_API_KEY = "sk-b479bd440ff94309aa6c691022c210a3";

    // 使用Catfact.ninja作为后备API - 这是一个免费的、不需要认证的API
    private static final String CAT_FACT_API = "https://catfact.ninja/fact";

    // 使用Public APIs作为另一个后备API
    private static final String PUBLIC_API = "https://api.publicapis.org/random";

    @Override
    public String getAIResponse(String question, String targetModel) {
        logger.info("请求AI服务，问题: {}, 目标模型: {}", question, targetModel);

        try {
            // 首先尝试使用DeepSeek API
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + DEEPSEEK_API_KEY);

            // 构建消息列表
            List<Map<String, String>> messages = new ArrayList<>();

            // 添加系统消息
            Map<String, String> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个学习助手，擅长回答学生的各类问题。请提供简洁、准确、有帮助的回答。");
            messages.add(systemMessage);

            // 添加用户消息
            Map<String, String> userMessage = new HashMap<>();
            userMessage.put("role", "user");
            userMessage.put("content", question);
            messages.add(userMessage);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("messages", messages);
            requestBody.put("stream", false);

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 发送POST请求并获取响应
            ResponseEntity<Map> response = restTemplate.postForEntity(
                    DEEPSEEK_API_URL,
                    requestEntity,
                    Map.class);

            logger.info("DeepSeek API响应状态: {}", response.getStatusCode());

            // 处理DeepSeek API响应
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    Map<String, String> message = (Map<String, String>) choice.get("message");
                    if (message != null && message.containsKey("content")) {
                        return message.get("content");
                    }
                }
            }

            // 如果DeepSeek API失败，尝试使用CatFact API作为后备
            ResponseEntity<Map> catFactResponse = restTemplate.getForEntity(CAT_FACT_API, Map.class);

            if (catFactResponse.getStatusCode().is2xxSuccessful() && catFactResponse.getBody() != null) {
                Map<String, Object> catFactResponseBody = catFactResponse.getBody();
                String catFact = (String) catFactResponseBody.get("fact");

                // 构建回复
                StringBuilder formattedResponse = new StringBuilder();
                formattedResponse.append("您的问题: ").append(question).append("\n\n");
                formattedResponse.append("AI回复: \n");

                // 如果问题与猫有关，直接使用猫咪事实
                if (question.toLowerCase().contains("猫") || question.toLowerCase().contains("cat")) {
                    formattedResponse.append("以下是一个关于猫的有趣事实: ").append(catFact);
                } else {
                    // 否则，作为学习助手提供一个类似于回答的格式化回复
                    formattedResponse.append("作为您的学习助手，我无法直接回答您的特定问题，但我可以分享一些有趣知识: \n");
                    formattedResponse.append(catFact).append("\n\n");
                    formattedResponse.append("对于您的问题：\"").append(question).append("\"，我建议您可以通过查阅相关教材或在线资源获取更详细的信息。");
                }

                return formattedResponse.toString();
            }

            // 如果猫事实API也失败，尝试使用公共API
            ResponseEntity<Map> publicApiResponse = restTemplate.getForEntity(PUBLIC_API, Map.class);

            if (publicApiResponse.getStatusCode().is2xxSuccessful() && publicApiResponse.getBody() != null) {
                Map<String, Object> responseBody2 = publicApiResponse.getBody();
                if (responseBody2.containsKey("entries")) {
                    Object entries = responseBody2.get("entries");
                    if (entries instanceof java.util.List && !((java.util.List) entries).isEmpty()) {
                        Map<String, Object> entry = (Map<String, Object>) ((java.util.List) entries).get(0);

                        // 构建回复
                        StringBuilder response2 = new StringBuilder();
                        response2.append("您的问题: ").append(question).append("\n\n");
                        response2.append("AI回复: \n");
                        response2.append("我是您的学习助手，现在我无法直接回答您的问题，但我可以推荐一个有趣的API资源：\n");
                        response2.append("名称: ").append(entry.get("API")).append("\n");
                        response2.append("描述: ").append(entry.get("Description")).append("\n");
                        response2.append("链接: ").append(entry.get("Link")).append("\n\n");
                        response2.append("希望这对您有所帮助！如有更多问题，请继续提问。");

                        return response2.toString();
                    }
                }
            }

            // 如果所有API都失败，返回一个友好的错误信息
            return "很抱歉，AI服务暂时无法回答您的问题: \"" + question +
                    "\"。我们的服务正在维护中，请稍后再试。作为学习助手，我建议您可以查阅相关教材或询问老师获取更多帮助。";

        } catch (Exception e) {
            logger.error("调用AI服务出错", e);
            return "AI服务暂时不可用，请稍后再试: " + e.getMessage();
        }
    }
}